package com.livepan.server;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.livepan.server.error.BusinessException;
import com.livepan.server.error.EmBusinessError;
import com.livepan.server.response.CommonReturnType;
import com.livepan.server.service.model.UserModel;
import org.apache.http.HttpResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class BaseController {

    @Autowired
    public RedisTemplate redisTemplate;

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handleException(HttpServletRequest request, Exception ex) {
        int status;
        String message;
        if (ex instanceof BusinessException) {
            BusinessException businessException = (BusinessException) ex;
            status = businessException.getErrCode();
            message = businessException.getErrMsg();
        } else {
            ex.printStackTrace();
            status = EmBusinessError.UNKNOW_ERROR.getErrCode();
            message = EmBusinessError.UNKNOW_ERROR.getErrMsg();
        }
        return CommonReturnType.create(null, status, message);
    }

    protected UserModel getUserModelFromSession() throws BusinessException {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            return null;
        }
        String token = "";
        for (Cookie cookie : cookies) {
            if (Objects.equals(cookie.getName(), "token")) {
                token = cookie.getValue();
                break;
            }
        }
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        String s = (String) redisTemplate.opsForValue().get(token);
        if (StringUtils.isEmpty(s)) {
            return null;
        }

        UserModel userModel = JSON.parseObject(s, UserModel.class);
        userModel.setToken(token);
        return userModel;
    }

    protected void assetUserLogin() {
        if (getUserModelFromSession() == null) {
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
    }

}
